package com.bbs.server;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.alibaba.fastjson.JSON;
import com.bbs.beans.Subject;
import com.bbs.server.GetSubmitBySubject.Download;

import manager.PersistentManager;

/*
 * 根据主题上拉加载更多
 * 最多20条
 */
public class GetMoreSubmits extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetMoreSubmits() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data, Upload.class);
        
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
		Session session = sf.openSession();

		Download download = new Download();

		Transaction tx = session.beginTransaction();

		try {
			Query q = session.createQuery("from Submit s where s.subject = ? and s.time < ? order by s.time desc");
			Subject subject = new Subject();
			subject.setId(upload.getSubjectId());
			q.setParameter(0, subject);
			String time=upload.getLastTime();
			q.setParameter(1, time);
		
			q.setMaxResults(20);//前20条

			download.setSubmits(q.list());
			tx.commit();
			download.setStatus(DownloadInfo.SUCCESS);
		} catch (Exception e) {
			download.setStatus(DownloadInfo.FAILED);
			tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

		System.out.println(JSON.toJSONString(download));
		response.getWriter().append(JSON.toJSONString(download));

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
     
	
	// 上行数据
		public static class Upload {
			Long subjectId;
	        String lastTime;
			public Long getSubjectId() {
				return subjectId;
			}

			public void setSubjectId(Long subjectId) {
				this.subjectId = subjectId;
			}
			public String getLastTime(){
				return lastTime;
			}
			public void setLastTime(String time){
				this.lastTime=time;
			}

		}


}
